package com.xjysx.xiaochetong.moudle;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import android.serialport.SerialPortConstants;
import android.serialport.SerialPortUtil;

import com.serialportlibrary.util.LogUtil;
import com.xjysx.xiaochetong.R;
import com.xjysx.xiaochetong.base.BaseActivity;
import com.xjysx.xiaochetong.entities.EndCountDownEvent;
import com.xjysx.xiaochetong.network.BaseBean;
import com.xjysx.xiaochetong.network.BaseObserver;
import com.xjysx.xiaochetong.network.Network;
import com.xjysx.xiaochetong.util.SignatureUtil;
import com.xjysx.xiaochetong.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xjysx.xiaochetong.network.Network.GET_TIME_PAY;
import static com.xjysx.xiaochetong.network.Network.GET_TIME_USE;

/**
 * Created by danjj on 2020/8/16 0016.
 */
public class SelectActivity extends BaseActivity {

    @BindView(R.id.view_ret)
    View viewRet;
    @BindView(R.id.view_cet)
    View viewCet;
    @BindView(R.id.view_chao)
    View viewChao;
    @BindView(R.id.view_tie)
    View viewTie;
    public static int RET = 1;
    public static int CET = 2;
    public static int CHAO = 3;
    public static int TIE = 4;
    @BindView(R.id.tv_hour)
    TextView tvHour;
    @BindView(R.id.tv_minute)
    TextView tvMinute;
    @BindView(R.id.tv_second)
    TextView tvSecond;


    private int type;
    private int time;

    private boolean started;

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            LogUtil.e(time + "");
            if (time > 0) {
                time--;
            }
            EventBus.getDefault().post(new EndCountDownEvent(1));
            preferences.edit().putInt("time", time).apply();
        }
    };
    Timer timer2 = new Timer();
    TimerTask task2 = new TimerTask() {
        @Override
        public void run() {
            getTimeUse();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setTime(EndCountDownEvent event) {
        setTimeTextView();
        if (time == 5 * 60) {//提示
            showDialog();
            timer2.schedule(task2, 0, 60000);
        }
        if (time == 0) {
            showEndDialog("套餐时间结束，请重新扫码");
            finish();
        } else if (time == -5) {
            finish();
        }

    }

    private void showEndDialog(String content) {
        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                            task = null;
                        }
                        if (timer2 != null) {
                            timer2.cancel();
                            timer2 = null;
                            task2 = null;
                        }
                        finish();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void getTimeUse() {
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(GET_TIME_USE, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private AlertDialog.Builder builder;

    private void showDialog() {
        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage("该套餐时长仅剩5分钟,如需修改,请联系管理员").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        builder.create().show();
    }


    private BaseObserver<Object> observer = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
            if (bean == null) {
                return;
            }
            if (((Map) bean).containsKey("time_pay")) {
                double time_pay = (double) ((Map) bean).get("time_pay");
                if (time_pay > 0) {
                    time = new Double(time_pay).intValue();//单位为秒
                    setTimeTextView();
                    if (preferences.getBoolean("started", false)) {
                        started = false;
                        timer.schedule(task, 0, 1000);
                    }
                }
            }
            if (((Map) bean).containsKey("time_use")) {
                double time_pay = (double) ((Map) bean).get("time_use");
                if (time_pay > 0) {
                    time = Double.valueOf(time_pay).intValue();//单位为秒
                    setTimeTextView();
                    if (time > 300) {
                        timer2.cancel();
                        timer2 = null;
                        task2 = null;
                        timer2 = new Timer();
                        task2 = new TimerTask() {
                            @Override
                            public void run() {
                                getTimeUse();
                            }
                        };
                    }
                }
            }
        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };

    private void setTimeTextView() {
        int hour = time / 60 / 60;
        int minute = time / 60 % 60;
        int second = time % 60;
        if (hour == 1 && minute == 0 && second == 0) {
            tvHour.setText("00");
            tvMinute.setText("60");
            tvSecond.setText("00");
        } else {
            tvHour.setText(hour < 10 ? "0" + hour : hour + "");
            tvMinute.setText(minute < 10 ? "0" + minute : minute + "");
            tvSecond.setText(second < 10 ? "0" + second : second + "");
        }
    }

    @Override
    protected void loadLayout() {
        setContentView(R.layout.activity_select);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    }

    @Override
    public void initPresenter() {
        EventBus.getDefault().register(this);
    }


    @Override
    protected void processLogic(Bundle savedInstanceState) {
        super.processLogic(savedInstanceState);
        started = preferences.getBoolean("started", false);
        SerialPortUtil.sendSerialPortByte(SerialPortConstants.RESET);
        if (!started) {
            getPayTime();
        } else {
            time = preferences.getInt("time", 0);
            setTimeTextView();
            timer.schedule(task, 0, 1000);
            if (time <= 300) {
                timer2.schedule(task2, 0, 60000);
            }
        }
    }

    private void getPayTime() {
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
        Network.getQrCode().getQrCode(GET_TIME_PAY, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
            task = null;
        }
        if (timer2 != null) {
            timer2.cancel();
            timer2 = null;
            task2 = null;
        }
    }


    @OnClick({R.id.view_ret, R.id.view_cet, R.id.view_chao, R.id.view_tie, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_ret:
                type = 1;
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                finish();
                break;
            case R.id.view_cet:
                type = 2;
                Intent intent2 = new Intent(this, MainActivity.class);
                intent2.putExtra("type", type);
                startActivity(intent2);
                finish();
                break;
            case R.id.view_chao:
                type = 3;
                Intent intent3 = new Intent(this, MainActivity.class);
                intent3.putExtra("type", type);
                startActivity(intent3);
                finish();
                break;
            case R.id.view_tie:
                type = 4;
                Intent intent4 = new Intent(this, MainActivity.class);
                intent4.putExtra("type", type);
                startActivity(intent4);
                finish();
                break;
            default:
                break;
        }

    }


}
